package com.byxy.ssm.demo.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.byxy.ssm.demo.entity.Items;
import com.byxy.ssm.demo.service.ItemsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("items")
public class ItemsController {
	@Value("${upload.path}")
	private String path;

	@Autowired
	private ItemsService itemsService;

	@RequestMapping(value = "add", method = RequestMethod.GET)
	public String add() {
		return "add";
	}

	@PostMapping("add")
	public String add2(Items item, MultipartFile imgFile, HttpServletRequest req) throws Exception, IOException {
		// String path =
		// req.getSession().getServletContext().getRealPath("static/images");
		if (path == null) {
			path = req.getSession().getServletContext().getRealPath("static/images");
			item.setImg("images/" + imgFile.getOriginalFilename());
		}
		else{
			File f = new File(path);
			if (!f.exists()) {
				f.mkdirs();
			}
			item.setImg("/images?filename=" + imgFile.getOriginalFilename());
		}
		System.out.println(path);
		imgFile.transferTo(new File(path, imgFile.getOriginalFilename()));		
		itemsService.save(item);
		return "redirect:list";
	}

	@GetMapping("list")
	public String list(Model model) {
		List<Items> items = itemsService.findAll();
		model.addAttribute("list", items);
		return "list";
	}

}
